<template>
  <div class="container">
    <h1>Electron UDP通信示例---Message</h1>

    <div class="control-panel">
      <div class="form-group">
        <label>本地端口:</label>
        <input v-model="localPort" type="number" placeholder="默认4125" />
      </div>

      <div class="form-group">
        <label>目标IP:</label>
        <input v-model="targetIp" placeholder="255.255.255.255" />
      </div>

      <div class="form-group">
        <label>目标端口:</label>
        <input v-model="targetPort" type="number" placeholder="4125" />
      </div>

      <div class="form-group">
        <label>消息内容:</label>
        <textarea v-model="message" placeholder="输入要发送的消息"></textarea>
      </div>

      <div class="button-group">
        <button @click="sendMessage">发送定向消息</button>
        <button @click="sendBroadcast">发送广播消息</button>
      </div>
    </div>

    <div class="message-container">
      <h2>接收到的消息</h2>
      <div class="message-list">
        <div v-for="(msg, index) in receivedMessages" :key="index" class="message">
          <div class="message-header">
            <span class="from">{{ msg.from.ip }}:{{ msg.from.port }}</span>
            <span class="time">{{ formatTime(msg.timestamp) }}</span>
          </div>
          <div class="message-content">{{ msg.message }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    const localPort = ref('51223')
    const targetIp = ref('192.168.174.128')
    const targetPort = ref('51223')
    const message = ref('')
    const receivedMessages = ref([])

    // 格式化时间
    const formatTime = isoString => {
      return new Date(isoString).toLocaleTimeString()
    }

    // 发送定向消息
    const sendMessage = () => {
      if (!message.value.trim()) return

      window.ipcRenderer.invoke('send-udp-message', {
        message: message.value,
        address: targetIp.value,
        port: parseInt(targetPort.value)
      })

      // // 添加到接收消息列表（模拟发送显示）
      // receivedMessages.value.push({
      //   message: message.value,
      //   from: {
      //     ip: '本地',
      //     port: parseInt(localPort.value)
      //   },
      //   timestamp: new Date().toISOString()
      // })

      message.value = ''
    }

    // 发送广播消息
    const sendBroadcast = () => {
      if (!message.value.trim()) return

      window.ipcRenderer.invoke('send-broadcast', message.value)

      // // 添加到接收消息列表（模拟发送显示）
      // receivedMessages.value.push({
      //   message: `[广播] ${message.value}`,
      //   from: {
      //     ip: '本地',
      //     port: parseInt(localPort.value)
      //   },
      //   timestamp: new Date().toISOString()
      // })

      message.value = ''
    }

    // 处理接收到的UDP消息
    const handleUDPMessage = (event, data) => {
      receivedMessages.value.push(data)
    }

    // 处理错误
    const handleUDPError = (event, error) => {
      console.error('UDP error:', error)
      // 可以在这里添加错误提示
    }

    // 接收到xx上线提醒
    const userLogin = (event, message) => {
      console.info(message)
      receivedMessages.value.push({
        message: `${message.userName}上线了`,
        from: {
          ip: message.address,
          port: parseInt(localPort.value)
        },
        timestamp: new Date().toISOString()
      })
    }

    // 生命周期钩子
    onMounted(() => {
      window.ipcRenderer.on('udp-message', handleUDPMessage)
      window.ipcRenderer.on('udp-error', handleUDPError)
      window.ipcRenderer.on('login-message', userLogin)
    })

    onUnmounted(() => {
      window.ipcRenderer.removeListener('udp-message', handleUDPMessage)
      window.ipcRenderer.removeListener('udp-error', handleUDPError)
      window.ipcRenderer.removeListener('login-message', userLogin)
    })

    return {
      localPort,
      targetIp,
      targetPort,
      message,
      receivedMessages,
      formatTime,
      sendMessage,
      sendBroadcast
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  height: calc(100vh - 80px);
}

h1 {
  text-align: center;
  color: #333;
}

.control-panel {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.button-group {
  display: flex;
  gap: 10px;
}

.button-group button {
  flex: 1;
  padding: 10px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.button-group button:hover {
  background-color: #3a7bc8;
}

.message-container {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
}

.message {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.message:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9em;
  color: #666;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
